package com.study.user.service.impl;

import org.apache.commons.httpclient.auth.AuthenticationException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import util.Constats;

import com.study.user.dao.UserMapper;
import com.study.user.pojo.User;
import com.study.user.service.UserService;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	UserMapper userDao;
	@Override
	public boolean validate(String username, String password) {
		boolean isLogin =false;
		User u=userDao.selectByUserName(username);
		if(u.getPassword().equals(password)){
			isLogin=true;
		}
		return isLogin;
	}
	@Override
	public User getUserName(String user_name){
		return userDao.selectByUserName(user_name);
	}
	@Override
	public int getUserConut(){
		return userDao.getUserCount();
	}
	@Override
	public boolean insertuser(String username,String password){
		if(userDao.detection(username)==0){
			User u=new User();
			u.setUserName(username);
			u.setPassword(password);
			int flag=userDao.insertByParams(u);
			if(flag >0){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
	@Override
	public User doLogin(String username, String password) {
		// TODO Auto-generated method stub
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken(username,password);
		try{
			subject.login(token);
			User user=getUserName(username);
			Session session=subject.getSession();
			session.setAttribute(Constats.SESSION_USER,user);
			return user;
		}catch(InvalidSessionException e){
			e.printStackTrace();
			return null;
		}
	}
	

}
